package example.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()

                //地址不是资源所在地址而是访问地址
                //范围小的放在前面，范围大的放在后面,这样范围小的就会生效
                .antMatchers("/level3/3").permitAll()
                .antMatchers("/level1/**").hasRole("aa")
                .antMatchers("/level3/**").hasRole("cc")
                .antMatchers("/level2/**").hasRole("bb");
                //.anyRequest().authenticated(); // 用户访问其它URL都必须认证后访问
        //没有权限就跳转到登陆页面
        http.formLogin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("1111").password(new BCryptPasswordEncoder().encode("12345")).roles("aa")
                .and()
                .withUser("2222").password(new BCryptPasswordEncoder().encode("12345")).roles("bb")
                .and()
                .withUser("3333").password(new BCryptPasswordEncoder().encode("12345")).roles("cc")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("12345")).roles("aa", "bb", "cc");
    }
}
